<template>
	<div class="zs-table-page-container">
		<div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
			<span>
				<el-select v-model="queryParams.projectCode" class="zs-select-md zs-space-right-sm" placeholder="项目名称">
					<el-option v-for="item in projectList" :key="item.project_code" :label="item.project_name"
						:value="item.project_code" />
				</el-select>
				<el-cascader class="zs-select-md zs-space-right-sm " v-model="queryParams.formatCode" :options="formatList"
					placeholder="业态名称" :props="cascaderProps" collapse-tags collapse-tags-tooltip clearable filterable />
				<el-date-picker class="zs-space-right-sm" v-model="queryParams.year" type="year" placeholder="年份"
					:clearable="false" value-format="YYYY" />
				<el-button class="zs-btn-plain" @click="getList()"> 查询 </el-button>
			</span>
			<span class="zs-layout-flex-row">
				<el-button class="zs-btn-plain" @click="handleDownload">
					<el-icon class="el-icon--left">
						<Upload />
					</el-icon>
					<span>导出</span>
				</el-button>
			</span>
		</div>
		<div class="zs-card zs-table-page-content">
			<hsTableV2 isMultistageHeader :columns="tableData.cloumns" :data="tableData.data" :loading="tableData.loading"
				:expendList="expandedRowKeys" isTree fixed expandColumnKey="id" :multistageHeaderData="multistageData"
				:rowClassFun="tableData.rowClass">
			</hsTableV2>
			<div class="zs-text-gray-dark zs-text-sm zs-space-top">*单位：万元；元/㎡/月；㎡</div>
		</div>
	</div>
</template>
<script setup lang="jsx">
import dbPublicApi from '@/api/dbPublic';
// import TableV2 from '@/components/tableV2';
import { brandFlatEffectListNewApi, getFormatDropDownApi, getBrandFlatEffectProjectDropDownApi, brandFlatEffectListExportApi } from '@/api/Manage/Business/plateauEffectAnalysis'
import { toThousands } from '@/utils/number-util'
import { ref, reactive, computed } from 'vue';
import { downloadNewFile } from '@/utils/publicUtils';
import { useRouter, useRoute } from 'vue-router';
let route = useRoute();
let { biProjectCode } = route.query
let router = useRouter();
let yearMonth = ref('') //年月:yyyy-MM 月报的日期
// 查询条件
let queryParams = reactive({
	formatCode: [],//业态code,多选逗号分隔,全部传'全部'
	projectCode: biProjectCode,//项目code
	year: '',//年月:yyyy-MM 月报的日期
})
let formatCodeStr = computed(() => {
	let str = '全部'
	if (queryParams.formatCode?.length) {
		let arr = queryParams.formatCode.flat(Infinity)
		let arr1 = [...new Set(arr)]
		str = arr1.join(',')
	}
	return str
});
const cascaderProps = { multiple: true, label: 'brandName', value: 'id' }
const formatList = ref([])
let projectList = ref([]) // 项目列表
const cloumnsFix = [
	{
		key: "id",
		dataKey: "id",
		title: "业态级别",
		align: "left",
		width: 100,
		fixed: true,
		cellRenderer: ({ rowData, rowIndex }) => (
			<div>{rowIndex == 0 ?  ' ' : `${rowData.format_type}级`}</div>
		)
	},
	{
		key: "format_code",
		dataKey: "format_code",
		title: "业态名称",
		width: 200,
		fixed: true,
		align: "left",
		indentKey: 'format_type', // 设置缩进字段
		cellRenderer: ({ rowData, rowIndex }) => (
			<div style={{ display: 'flex' }}>
				<div style={{ width: `${12 * (Number(rowData.format_type) - 1)}px`, flexShrink: 0 }}></div>
				{/* <div class={rowData.format_type == 3 ? 'jump' : ''} onClick={() => jumpDetailPage(rowData)}>{rowData.format_code}</div> */}
				{/* <div class={'jump'} onClick={() => jumpDetailPage(rowData)}>{rowData.format_code}</div> */}
				<div class={`${rowIndex == 0 ? '' : 'zs-pointer zs-text-blue'}`} onClick={() => rowIndex == 0 ? '' : jumpDetailPage(rowData)}>{rowData.format_code}</div>
			</div>
		)
	},
	{
		key: `totalSales`,
		dataKey: `totalSales`,
		title: "销售额",
		align: "right",
		width: 100,
		parentKey: `multCol_total`,
		cellRenderer: ({ rowData }) => (
			rowData[`totalSales`]
		)
	},
	{
		key: `totalInvrecamtl`,
		dataKey: `totalInvrecamtl`,
		title: "租费",
		align: "right",
		width: 100,
		parentKey: `multCol_total`,
		cellRenderer: ({ rowData }) => (
			rowData[`totalInvrecamtl`]
		)
	},
	{
		key: `totalMonthlySalesPerSqm`,
		dataKey: `totalMonthlySalesPerSqm`,
		title: "月均坪效",
		align: "right",
		width: 100,
		parentKey: `multCol_total`,
		cellRenderer: ({ rowData }) => (
			rowData[`totalMonthlySalesPerSqm`]
		)
	},
	{
		key: `totalRentalSalesRatio`,
		dataKey: `totalRentalSalesRatio`,
		title: "租费比",
		align: "right",
		width: 100,
		parentKey: `multCol_total`,
		cellRenderer: ({ rowData }) => (
			rowData[`totalRentalSalesRatio`]
		)
	},
]
let tableData = ref({
	loading: false,
	data: [],
	cloumns: [],
	rowClass: ({ rowData, rowIndex }) => {
		if (rowIndex == 0) {
			return 'db-table-row-yellow';
		}
		if (rowData.format_type == 1) {
			return 'db-table-row-blue-dark';
		}
		if (rowData.format_type == 2) {
			return 'Level2Row';
		}
		if (rowData.format_type == 3) {
			return 'zs-text-gray';
		}
	},
})


let expandedRowKeys = ref([])
const convertToFlatArray = (arr) => {
	arr.map(item => {
		item.lastStage = item.format_type == 3 ? 1 : 0 // 设置:是否为最后一级 是末级 但不是第一级 变灰色
		// item.format_type == 1 || item.format_type == 2 ? expandedRowKeys.value.push(item.id) : '' // 第一级 第二级 默认展开
		if (Array.isArray(item.children)) {
			convertToFlatArray(item.children);
		}
		return item
	})
}
const jumpDetailPage = (rowData) => {
	// if (rowData.lastStage != 1) return
	let query = {
		// brandName: '全部',//品牌名称
		projectCode: rowData.project_code,//项目编码
		yearMonth: yearMonth.value,//数据更新年月
		year: rowData.year,//当前行年
		firstFormat: rowData.format_type == 1 ? rowData.wt_format : null,//1级业态
		secondFormat: rowData.format_type == 2 ? rowData.wt_format : null,//2级业态
		thirdFormat: rowData.format_type == 3 ? rowData.wt_format : null,//3级业态
		rTitle: '品牌坪效明细报表',
	};
	console.log(query)
	router.push({
		path: '/Manage/Business/plateauEffectAnalysis/detailList',
		query,
	});
}
const getOptionList = async () => {
	// 业态
	let res1 = await getFormatDropDownApi()
	if (res1.data.errorCode == 200) {
		formatList.value = res1.data.data
	}
	// 项目
	let res2 = await getBrandFlatEffectProjectDropDownApi()
	if (res2.data.errorCode == 200) {
		projectList.value = res2.data.data;
	}
	//月份
	let res3 = await dbPublicApi.queryMonthsTimeApi()
	if (res3.data.code == 200) {
		yearMonth.value = res3.data.data
		queryParams.year = res3.data.data.split('-')[0]
	}
	getList()
}
getOptionList()
const getList = () => {
	test.value++
	tableData.value.loading = true
	let params = Object.assign({}, queryParams);
	params.formatCode = formatCodeStr.value
	brandFlatEffectListNewApi(params).then((res) => {
		if (res.data.errorCode == 200 && res.data.data) {
			const selectYearMonth = Number(queryParams.year) < Number(yearMonth.value.split('-')[0]) ? `${queryParams.year}-12` :
				Number(queryParams.year) == Number(yearMonth.value.split('-')[0]) ? yearMonth.value :
					Number(queryParams.year) > Number(yearMonth.value.split('-')[0]) ? `${queryParams.year}-12` : ''
			initMultistageData(selectYearMonth)
			convertToFlatArray(res.data.data)
			tableData.value.data = res.data.data
		} else {
			tableData.value.data = []
		}
	}).finally(() => {
		tableData.value.loading = false
	})
}
//合并表头
const multistageData = {}
let test = ref(0)
const initMultistageData = (queryTime) => {
	tableData.value.cloumns = cloumnsFix

	multistageData[`multCol_total`] = {
		key: `multCol_total`,
		title: `累计`,
		childrenIndex: [2,3,4,5]
	}

	let startIndex = 6 //月份数据列起点索引值
	let keyCount = 6 //每组数据字段数
	let num = new Date(queryTime).getMonth() + 1 // 几个月
	// let month = new Date(queryTime).getMonth() + 1 //当前月份
	let year = new Date(queryTime).getFullYear() //当前年

	let windowWidth = document.documentElement.scrollWidth
	let minWidth = (windowWidth - 138 - 100 - 200 - 4*100) / (num * 6)
	let width = minWidth < 100 ? 100 : minWidth

	for (let i = num; i > 0; i--) {
		let arr = []
		for (let j = 0; j < keyCount; j++) {
			arr[j] = startIndex
			startIndex++
		}
		multistageData[`multCol_${i}`] = {
			key: `multCol_${i}`,
			title: `${year}年${i}月`,
			childrenIndex: arr
		}
		const groupCol = [
			{
				key: `barnd_count_${i}`,
				dataKey: `barnd_count_${i}`,
				title: "商铺数量",
				align: "right",
				width: width,
				parentKey: `multCol_${i}`,
				cellRenderer: ({ rowData }) => (
					rowData[`barnd_count_${i}`]
				)
			},
			{
				key: `usablearea_${i}`,
				dataKey: `usablearea_${i}`,
				title: "租赁面积",
				align: "right",
				width: width,
				parentKey: `multCol_${i}`,
				cellRenderer: ({ rowData }) => (
					rowData[`usablearea_${i}`]
				)
			},
			{
				key: `day_sales_${i}`,
				dataKey: `day_sales_${i}`,
				title: "销售额",
				align: "right",
				width: width,
				parentKey: `multCol_${i}`,
				cellRenderer: ({ rowData }) => (
					toThousands(rowData[`day_sales_${i}`])
				)
			},
			{
				key: `monthly_sales_per_sqm_${i}`,
				dataKey: `monthly_sales_per_sqm_${i}`,
				title: "月坪效",
				align: "right",
				width: width,
				parentKey: `multCol_${i}`,
				cellRenderer: ({ rowData }) => (
					toThousands(rowData[`monthly_sales_per_sqm_${i}`])
				)
			},
			{
				key: `invrecamtl_${i}`,
				dataKey: `invrecamtl_${i}`,
				title: "月租费",
				align: "right",
				width: width,
				parentKey: `multCol_${i}`,
				cellRenderer: ({ rowData }) => (
					toThousands(rowData[`invrecamtl_${i}`])
				)
			},
			{
				key: `rental_sales_ratio_${i}`,
				dataKey: `rental_sales_ratio_${i}`,
				title: "租售比",
				align: "right",
				width: width,
				parentKey: `multCol_${i}`,
				cellRenderer: ({ rowData }) => (
					rowData[`rental_sales_ratio_${i}`]
				)
			},
		]
		tableData.value.cloumns = tableData.value.cloumns.concat(groupCol)
	}
}

// 导出
const handleDownload = async () => {
	const fileName = `品牌坪效分析报表.xls`;
	let fileData;
	let params = Object.assign({}, queryParams);
	params.formatCode = formatCodeStr.value
	await brandFlatEffectListExportApi(params).then(res => {
		fileData = res.data;
	});
	downloadNewFile(fileData, fileName);
};
</script>
<style lang="scss" scoped></style>
